<template>
	<uniPpopup v-model="value" type="bottom" @close="close">
		<view class="content-box">
			<view class="response text-center" v-if="isChooseP&&!isChooseAll">
				<view class="cu-btn radius bg-main response " @tap="confirmData">确认选择</view>
			</view>
			<scroll-view scroll-x class="nav u-scroll-view" scroll-with-animation :scroll-left="scrollLeft" v-if="value">
				<view class="flex align-center">
					<view class="cu-item padding-lr padding-tb-sm" :class="index==tabsIndex?'text-main current text-bold':''" v-for="(item,index) in genTabsList" :key="index" @tap="tabsChange(index)">
						{{item['name']}}
					</view>
				</view>
				
			</scroll-view>
			<view class="area-box">
				<view class="flex align-center" :class="{ 'change':isChange }">
					<view class="area-item">
						<view class="padding-xs" style="height: 100%;">
							<scroll-view :scroll-y="true" style="height: 100%">
								<view class="padding-tb-sm" v-for="(item,index) in provinces" :key="index" @click="provinceChange(item.id,index)">
									<text :class="(isChooseP&&province===index)?'text-main':''">{{item[labelName]}}</text> 
									<text class="cuIcon-check icon-lg text-bold text-main margin-left-sm" v-if="isChooseP&&province===index"></text>
								</view>
							</scroll-view>
						</view>
					</view>
					<view class="area-item">
						<view class="padding-xs" style="height: 100%;">
							<scroll-view :scroll-y="true" style="height: 100%">
								<view class="" v-if="isChooseP">
									<view class="padding-tb-sm" v-for="(item,index) in citys" :key="index" @click="cityChange(item.id,index)">
										<text :class="(isChooseC&&city===index)?'text-main':''">{{item[labelName]}}</text>
										<text class="cuIcon-check icon-lg text-bold text-main margin-left-sm" v-if="isChooseC&&city===index"></text>
									</view>
								</view>
							</scroll-view>
						</view>
					</view>
			
					<view class="area-item">
						<view class="padding-xs" style="height: 100%;">
							<scroll-view :scroll-y="true" style="height: 100%">
								<view class="" v-if="isChooseC">
									<view class="padding-tb-sm" v-for="(item,index) in areas" :key="index" @click="areaChange(item.id,index)">
										<text :class="(isChooseA&&area===index)?'text-main':''">{{item[labelName]}}</text>
										<text class="cuIcon-check icon-lg text-bold text-main margin-left-sm" v-if="isChooseA&&area===index"></text>
									</view>
								</view>
							</scroll-view>
						</view>
					</view>
					
					<view class="area-item">
						<view class="padding-xs" style="height: 100%;">
							<scroll-view :scroll-y="true" style="height: 100%">
								<view class="" v-if="isChooseA">
									<view class="padding-tb-sm" v-for="(item,index) in streets" :key="index" @click="streetChange(item.fullPath,index)">
										<text :class="(isChooseS&&street===index)?'text-main':''">{{item[labelName]}}</text>
										<text class="cuIcon-check icon-lg text-bold text-main margin-left-sm" v-if="isChooseS&&street===index"></text>
									</view>
								</view>
							</scroll-view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</uniPpopup>
</template>

<script>
	import uniPpopup from "@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue"
	/**
	 * city-select 省市区级联选择器
	 * @property {String Number} z-index 弹出时的z-index值（默认1075）
	 * @property {Boolean} mask-close-able 是否允许通过点击遮罩关闭Picker（默认true）
	 * @property {String} default-region 默认选中的地区，中文形式
	 * @property {String} default-code 默认选中的地区，编号形式
	 */
	export default {
		name: 'city-select',
		components:{
			uniPpopup
		},
		props: {
			// 通过双向绑定控制组件的弹出与收起
			value: {
				type: Boolean,
				default: false
			},
			// 默认显示的地区，可传类似["河北省", "秦皇岛市", "北戴河区"]
			// defaultRegion: {
			// 	type: Array,
			// 	default () {
			// 		return [];
			// 	}
			// },
			// 默认显示地区的编码，defaultRegion和areaCode同时存在，areaCode优先，可传类似"51,5133,513337,513337102"
			areaCode: {
				type: String,
				default () {
					return '';
				}
			},
			// 是否允许通过点击遮罩关闭Picker
			maskCloseAble: {
				type: Boolean,
				default: true
			},
			// 弹出的z-index值
			zIndex: {
				type: [String, Number],
				default: 0
			},
			//是否直接选择省市区，false可只选择省或者市
			isChooseAll: {
				type: Boolean,
				default: true
			},
		},
		data() {
			return {
				scrollLeft:0,
				cityValue: "",
				isChooseP: false, //是否已经选择了省
				province: 1, //省级Id
				provinces: [],
				isChooseC: false, //是否已经选择了市
				city: 0, //市级Id
				citys: [],
				isChooseA: false, //是否已经选择了区
				area: 0, //区级Id
				areas: [],
				tabsIndex: 0,
				street:0, //街道Id
				isChooseS:false, // 是否已经选择了街道
				streets:[],
				labelName:'shortName'
			}
		},
		mounted() {
			this.getRegionProvinces();
			console.log(this.value,1234)
		},
		watch:{
			areaCode(newValue, oldValue) {
				this.init();
			}
		},
		computed: {
			isChange() {
				return this.tabsIndex > 1;
			},
			genTabsList() {
				let tabsList = [{
					name: "请选择"
				}];
				if (this.isChooseP) {
					tabsList[0]['name']=this.provinces[this.province][this.labelName]
					tabsList[1] = {
						name: "请选择"
					};
				}
				if (this.isChooseC) {
					tabsList[1]['name'] =this.citys[this.city][this.labelName]
					if(this.areas.length){
						tabsList[2] = {
							name: "请选择"
						}
					}
				}
				if (this.isChooseA) {
					tabsList[2]['name'] = this.areas[this.area][this.labelName]
					if(this.streets.length){
						tabsList[3] = {
							name: "请选择"
						};
					}
						
				}
				if (this.isChooseS) {
					tabsList[3]['name'] = this.streets[this.street][this.labelName]
				}
				return tabsList;
			},
			// uZIndex() {
			// 	// 如果用户有传递z-index值，优先使用
			// 	return this.zIndex ? this.zIndex : this.$u.zIndex.popup;
			// },
			
		},
		methods: {
			async init() {
				if(this.areaCode&&this.areaCode.length){
					let areaCode=this.areaCode.split(',')
					let areaName=''
					this.provinces.map((v, k) => {
						if ( v.id == areaCode[0]) {
							this.isChooseP = true;
							this.isChooseC = false;
							this.isChooseA = false;
							this.isChooseS = false;
							this.province = k;
							areaName=v[this.labelName]
							console.log(areaName,1)
						}
					})
					if(areaCode.length>=2){
						await this.initDatas(areaCode[0],1).then(()=>{
							this.citys.map((v, k) => {
								if (v.id == areaCode[1]) {
									this.isChooseC = true;
									this.isChooseA = false;
									this.isChooseS = false;
									this.city = k;
									areaName=areaName+v[this.labelName]
									console.log(areaName,2)
								}
							})
						})
					}
					if(areaCode.length>=3){
						let code=areaCode[1]
						await this.initDatas(code,2).then(()=>{
							this.areas.map((v, k) => {
								if (v.id == areaCode[2]) {
									this.isChooseA = true;
									this.isChooseS = false;
									this.area = k;
									areaName=areaName+v[this.labelName]
									console.log(areaName,3)
								}
							})
						})
					}
					if(areaCode.length>=4){
						let code=areaCode[2]
						await this.initDatas(code,3).then(()=>{
							this.streets.map((v, k) => {
								if (v.id == areaCode[3]) {
									this.isChooseS = true;
									this.street = k;
									areaName=areaName+v[this.labelName]
								}
							})
						})
					}
					console.log(areaName)
					this.$nextTick(()=>{
						this.$emit('init-data',areaName)
					})
				}
			},
			async initDatas(id,type){
				await this.$ajax.GetAreas({AreasId:id}).then(res=>{
					if(type==1){
						this.citys=res.data
						this.tabsIndex = 1;
					}else if(type==2){
						this.areas=res.data
						this.tabsIndex = 2;
					}else{
						this.streets=res.data
						this.tabsIndex = 3;
					}
				}).catch(err=>{
					
				})
			},
			//获取所有省
			getRegionProvinces() {
				this.$ajax.GetAreas().then((res)=>{
					this.provinces=res.data
					this.init()
				}).catch(err=>{
					// console.log(err,55555)
				})
			},
			// 根据父id获取下级地址
			getDatas(id,type) {
				this.$ajax.GetAreas({AreasId:id}).then((res)=>{
					if(type==1){
						this.citys=res.data
						this.tabsIndex = 1;
					}else if(type==2){
						this.areas=res.data
						if(this.areas.length){
							this.tabsIndex = 2;
						}else{
							let result = {};
							result.province = this.provinces[this.province];
							result.city = this.citys[this.city];
							this.$emit('city-change', result);
							this.close();
						}
						
					}else{
						this.streets=res.data
						if(this.streets.length){
							this.tabsIndex = 3;
						}else{
							let result = {};
							result.province = this.provinces[this.province];
							result.city = this.citys[this.city];
							result.area = this.areas[this.area];
							this.$emit('city-change', result);
							this.close();
						}
						
					}
				}).catch(err=>{
					
				})
			},
			setProvince(label = "", value = "") {
				return new Promise((res,rej)=>{
					this.provinces.map((v, k) => {
						if (value ? v.id == value : v[this.labelName] == label) {
							this.provinceChange(v.id,k);
						}
					})
				})
				
			},
			setCity(label = "", value = "") {
				return new Promise((res,rej)=>{
					this.citys.map((v, k) => {
						if (value ? v.id == value : v[this.labelName] == label) {
							this.cityChange(v.id,k);
						}
					})
					res('3245');
				})
			},
			setArea(label = "", value = "") {
				return new Promise((res,rej)=>{
					this.areas.map((v, k) => {
						if (value ? v.id == value : v[this.labelName] == label) {
							this.areaChange(v.id,k)
						}
					})
					res('3245');
				})
				
			},
			setStreet(label = "", value = "") {
				this.streets.map((v, k) => {
					if (value ? v.id == value : v[this.labelName] == label) {
						this.isChooseS = true;
						this.street = k;
					}
				})
			},
			close() {
				this.scrollLeft = (this.tabsIndex - 1) * 60;
				this.$emit('input', false);
			},
			tabsChange(index) {
				this.tabsIndex = index;
				this.scrollLeft = (index - 1) * 60;
			},
			provinceChange(id,index) {
				this.isChooseP = true;
				this.isChooseC = false;
				this.isChooseA = false;
				this.isChooseS = false;
				this.province = index;
				this.getDatas(id,1)
			},
			cityChange(id,index) {
				this.isChooseC = true;
				this.isChooseA = false;
				this.isChooseS = false;
				this.city = index;
				this.getDatas(id,2);
			},
			areaChange(id,index) {
				this.isChooseA = true;
				this.isChooseS =false;
				this.area = index;
				// this.getDatas(id,3);
				// this.isChooseS = true;
				let result = {};
				result.province = this.provinces[this.province];
				result.city = this.citys[this.city];
				result.area = this.areas[this.area];
				this.$emit('city-change', result);
				this.close();
			},
			streetChange(id,index) {
				this.isChooseS = true;
				this.street = index;
				let result = {};
				result.province = this.provinces[this.province];
				result.city = this.citys[this.city];
				result.area = this.areas[this.area];
				result.street = this.streets[this.street]
				this.$emit('city-change', result);
				this.close();
			},
			confirmData(){
				let result = {};
				if(this.isChooseP){
					result.province = this.provinces[this.province];
				}
				if(this.isChooseC){
					result.city = this.citys[this.city];
				}
				if(this.isChooseA){
					result.area = this.areas[this.area];
				}
				if(this.isChooseS){
					result.street = this.streets[this.street]
				}
				console.log(result,'result')
				this.$emit('city-change', result);
				this.close();
			}
		}

	}
</script>
<style lang="scss">
	.content-box{
		height: 900rpx;
		padding: 20rpx;
		background: #FFFFFF;
		.u-scroll-view {
			width: 100%;
			display: flex;
			align-items: center;
			white-space: nowrap;
			position: relative;
			.current{
				position: relative;
				&::after{
					content: "";
					position: absolute;
					bottom: 10rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					background-color:#77b14b;
					height: 3px;
					border-radius: 3px;
				}
			}
		}
		
		.u-tab-item {
			position: relative;
			/* #ifndef APP-NVUE */
			display: inline-block;
			/* #endif */
			text-align: center;
			transition-property: background-color, color;
		}
		
		.u-tab-bar {
			position: absolute;
			bottom: 0;
		}
		
		.u-tabs-scorll-flex {
			// @include vue-flex;
			justify-content: space-between;
		}
		.area-box {
			width: 100%;
			overflow: hidden;
			height: 800rpx;
		
			>view {
				width: 150%;
				transition: transform 0.3s ease-in-out 0s;
				transform: translateX(0);
		
				&.change {
					transform: translateX(-33.3333333%);
				}
			}
		
			.area-item {
				width: 33.3333333%;
				height: 800rpx;
			}
		}
	}
	
</style>
